/*
 * Camera.cpp
 *
 *  Created on: 31/05/2014
 *      Author: javier
 */

#include "Camera.h"

Camera::Camera() {
	this->levelWidth = 0;
	this->levelHeight = 0;
	this->screenWidth = properties.getPropertyAsInt("screen.width");
	this->screenHeight = properties.getPropertyAsInt("screen.height");
	this->target = NULL;
}

void Camera::update() {
	if (!target)
		return;
	std::pair<int, int> viewCoords = conv.convertToScreen(target->getX(),
			target->getY());
	int diffWidth = levelWidth - screenWidth;
	int diffHeight = levelHeight - screenHeight;
	if (diffWidth < 0) {
		offset.first = diffWidth / 2;
	} else {
		offset.first = viewCoords.first - screenWidth / 2;
		if (offset.first < 0) {
			offset.first = 0;
		}
		if (offset.first > diffWidth) {
			offset.first = diffWidth;
		}
	}

	if (diffHeight < 0) {
		offset.second = diffHeight / 2;
	} else {
		offset.second = viewCoords.second - screenHeight / 2;
		if (offset.second < 0) {
			offset.second = 0;
		}
		if (offset.second > diffHeight) {
			offset.second = diffHeight;
		}
	}

}

Camera::~Camera() {
	// TODO Auto-generated destructor stub
}

void Camera::setTarget(Positionable* p) {
	this->target = p;
}

SDL_Rect Camera::getOffsetFromModel(std::pair<double, double>& position) {
	SDL_Rect geometry = { 0, 0, 0, 0 };
	std::pair<int, int> viewCoords = conv.convertToScreen(position.first,
			position.second);
	int tile = properties.getPropertyAsInt("tile.size");
	geometry.x = viewCoords.first - tile / 2;
	geometry.x -= offset.first;
	geometry.y = viewCoords.second - tile / 2;
	geometry.y -= offset.second;
	geometry.w = tile;
	geometry.h = tile;
	return geometry;
}

void Camera::setLevelHeightTiles(int levelHeight) {
	this->levelHeight = levelHeight * properties.getPropertyAsInt("tile.size");
}

void Camera::setLevelWidthTiles(int levelWidth) {
	this->levelWidth = levelWidth * properties.getPropertyAsInt("tile.size");
}
